package com.smart.seckilldemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.smart.seckilldemo.commons.Parameters;
import com.smart.seckilldemo.mapper.SeckillGoodsMapper;
import com.smart.seckilldemo.mapper.SeckillOrderMapper;
import com.smart.seckilldemo.pojo.SeckillGoods;
import com.smart.seckilldemo.pojo.SeckillOrder;
import com.smart.seckilldemo.service.SeckillOrderService;
import com.smart.seckilldemo.utils.RedisJudgeUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SeckillOrderServiceImpl<PeerLimit> implements SeckillOrderService {


    @Resource
    SeckillOrderMapper seckillOrderMapper;
    @Resource
    RedisJudgeUtils redisJudgeUtils;

    /**、
     * 判断用户是否重复购买
     * @param userId
     * @param goodsId
     * @return
     */
    @Override

    public Boolean getOrderThere(Long userId,Long goodsId,Integer number) {
        //获取秒杀商品表
        String redisKey= Parameters.SeckillGoodsDateCache+":"+goodsId;
        SeckillGoods seckillGoods = (SeckillGoods) redisJudgeUtils.getRed(redisKey);
        //用户重复购买标记
        String RepetitionKry="Repetition"+userId+":"+goodsId;
        //判断缓存中的标识
        String red = (String) redisJudgeUtils.getRed(RepetitionKry);
        if(red!=null){
            //有标识直接返回
            if(red.equals("unlimited")){
                return true;
            }else {
                return false;
            }
        }
            //获取限制数量
             int size = seckillGoods.getPeerLimit();
            //获取该用户已经购买的数量
            QueryWrapper<SeckillOrder> qw = new QueryWrapper<>();
            qw.eq(SeckillOrder.COL_USER_ID,userId).eq(SeckillOrder.COL_GOODS_ID,goodsId);
            List<SeckillOrder> seckillOrders = seckillOrderMapper.selectList(qw);
            //最大限购数量减去 已有订单数量 得到可购买数量

        //用户限制购买数量
        if(size==(-1)){
            //标记 -1为无限制
            redisJudgeUtils.setRed(RepetitionKry,"unlimited");
            return true;
        }
        if(size>seckillOrders.size()){
            return true;
        }else {
            //标记该用户不允许购买
            redisJudgeUtils.setRed(RepetitionKry,"");
            return false;
        }
    }

    /**
     * 添加订单
     * @param seckillOrder
     * @return
     */
    @Override
    public Integer insertOrder(SeckillOrder seckillOrder) {
        int insert = seckillOrderMapper.insert(seckillOrder);
        return insert;
    }



}
